package cc.higou.service;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.ServletContext;
import java.io.*;
import java.util.Map;

@Service("staticPageService")
public class StaticPageServiceImpl implements StaticPageService, ServletContextAware {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;


    private ServletContext servletContext;

    @Override
    public void staticProductPage(Map<String, Object> map, String id) throws IOException, TemplateException {
        //使用spring的Freemarker配置获得标准的Freemark配置器
        Configuration configuration = freeMarkerConfigurer.getConfiguration();

        //生成的文件的位置
        String path = servletContext.getRealPath("/html/product/" + id + ".html");

        //判断路径成不成立
        System.out.println(path);
      File file = new File(path);
        //获取上一级的目录
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        //加载模版文件
        Template template = configuration.getTemplate("product.html");

        //设置文件输出的位置
       // Writer out = new FileWriter(new File(path));
        Writer out = new OutputStreamWriter(new FileOutputStream(new File(path)), "utf-8");
        //开始静态化
        template.process(map, out);

    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
